<template>
    <!--按钮区域-->
    <div style="margin-bottom: 10px;float:left; text-align:left">
        <el-button @click="onAdd">
            <el-icon style="margin-right: 6px;">
                <CirclePlus />
            </el-icon>
            手动新增
        </el-button>
        <el-button @click="onSync">
            <el-icon style="margin-right: 6px;">
                <Refresh />
            </el-icon>
            同步表结构
        </el-button>
        <el-button type="primary" @click="onSave">
            <el-icon style="margin-right: 6px;">
                <CircleCheck />
            </el-icon>
            保存
        </el-button>
    </div>

    <!--列表区域-->
    <div class="tableDataArea">
        <el-table :data="tableData" height="100%" highlight-current-row
            style="width: 100%; font-size: 12px; border-radius: 4px; border: 1px solid #eee" :header-cell-style="{
                background: '#fafafa',
                color: '#333',
                fontWeight: '600',
                fontSize: '14px'
            }">
            <el-table-column type="index" width="50" />

            <el-table-column label="中文名*" width="160">
                <template #default="scope">
                    <el-input v-model="scope.row.name" />
                </template>
            </el-table-column>
            <el-table-column label="字段名*" width="180">
                <template #default="scope">
                    <el-input v-model="scope.row.columnName" />
                </template>
            </el-table-column>
            <el-table-column label="列表中显示" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.showInTable" active-value="1" inactive-value="0" />
                </template>
            </el-table-column>
            <el-table-column label="列表查询条件" width="120">
                <template #default="scope">
                    <el-switch v-model="scope.row.isQueryParm" active-value="1" inactive-value="0" />
                </template>
            </el-table-column>
            <el-table-column label="可空" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.isNil" active-value="1" inactive-value="0" />
                </template>
            </el-table-column>
            <el-table-column label="主键" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.isPk" active-value="1" inactive-value="0" />
                </template>
            </el-table-column>
            <el-table-column label="可编辑" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.isEditable" active-value="1" inactive-value="0" />
                </template>
            </el-table-column>
            <el-table-column label="编辑方式" width="180">
                <template #default="scope">
                    <el-select v-model="scope.row.editType" class="m-2" placeholder="Select" size="large">
                        <el-option v-for="item in editTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </template>
            </el-table-column>
            <!--
            <el-table-column label="编辑域控制参数" >
                <template #default="scope">
                    <el-input v-model="scope.row.editParm" readonly>
                        <template #append>
                            <el-button style="color:#2597b9" link size="small"
                                @click="handleClickDelete(scope.$index)">修改</el-button>
                        </template>
                    </el-input>
                </template>
            </el-table-column>
            -->


            <el-table-column fixed="right" label="操作" width="200">
                <template #default="scope">
                    <el-button :icon="Delete" link type="primary" size="small"
                        @click="handleClickDelete(scope.$index)">删除</el-button>
                    <el-button :icon="Top" v-if="scope.$index > 0" link type="primary" size="small"
                        @click="handleClickUp(scope.$index)">上移</el-button>
                    <el-button :icon="Bottom" v-if="scope.$index < (tableData.length - 1)" link type="primary" size="small"
                        @click="handleClickDown(scope.$index)">下移</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script lang="ts" setup>
import { Delete, Top, Bottom } from '@element-plus/icons-vue'

import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps(['tableId', 'fields', 'tableName'])
const emit = defineEmits(['SaveSuccess'])


const tableData = reactive([]);
const editTypeOptions = reactive([
    {
        label: '输入框',
        value: 'input'
    },
    {
        label: '文本输入框',
        value: 'textarea'
    },
    {
        label: '日期选择',
        value: 'date'
    },
    {
        label: '日期时间选择',
        value: 'datetime'
    },
    {
        label: '下拉列表',
        value: 'select'
    },
    {
        label: '单选',
        value: 'radio'
    },
    {
        label: '开关',
        value: 'switch'
    },
])

onMounted(() => {

    if (props.fields != null && props.fields != "") {
        var inParmFields = JSON.parse(props.fields);
        for (var i = 0; i < inParmFields.length; i++) {
            tableData.push(inParmFields[i]);
        }
    }

})

const onAdd = () => {
    tableData.push({});
}

// 根据表名称，同步数据表结构
const onSync = () => {
    axios.post("/api/cg/table/getFields",
        {
            'tableName': props.tableName
        }).then(res => {
            console.log(res.data);
            if (res.data.code == "200") {
                //请添加执行成功后的业务代码 
                if(res.data.data.columns != null){
                    for( var i = 0 ; i < res.data.data.columns.length ; i++ ){
                        var rowItem = {
                            name: res.data.data.columns[i].remarks,
                            columnName : res.data.data.columns[i].columnName,
                            showInTable: '1',
                            isQueryParm: '0',
                            isPk:'0',
                            isEditable:'1',
                            isNil: res.data.data.columns[i].isNullAble == 'YES' ? '1' : '0',
                            editType:'input',
                            editParm:''
                        }
                        tableData.push(rowItem);
                    }
                }
            } else {
                // 错误消息为：res.data.msg 
                // 请添加执行失败后的业务代码 
            }
        });

}

const onSave = () => {

    var pkCnt = 0;
    // 循环判断有效性
    for( var i = 0 ; i < tableData.length ; i++){
        if(tableData[i].name == null || tableData[i].name == ""){
            ElMessage.error("请输入第" + (i+1) + "行的（中文）名称");
            return;
        }
        if(tableData[i].columnName == null || tableData[i].columnName == ""){
            ElMessage.error("请输入第" + (i+1) + "行的字段名称");
            return;
        }

        if(tableData[i].isPk == "1"){
            pkCnt++;
        }
    }
    if(pkCnt == 0){
        ElMessage.error("请选择一个字段作为主键（必须有1个）");
        return;
    }
    if(pkCnt > 1){
        ElMessage.error("请选择的主键字段过多（只能有1个）");
        return;
    }

    var ls_fields = JSON.stringify(tableData);

    // import axios from 'axios' 
    axios.post("api/cg/table/updateFields",
        {
            'id': props.tableId,
            'fields': ls_fields
        }).then(res => {
            if (res.data.code == "200") {
                ElMessage.success("保存成功")
                emit('SaveSuccess' , props.tableId , ls_fields)
                //请添加执行成功后的业务代码 
            } else {
                ElMessage.error("保存失败，失败信息为：" + res.data.msg)
                // 错误消息为：res.data.msg 
                // 请添加执行失败后的业务代码 
            }
        });
}

// 删除一行
const handleClickDelete = (index: number) => {
    tableData.splice(index, 1)
}

// 上移
const handleClickUp = (index: number) => {
    let temp = tableData[index];

    tableData[index] = tableData[index - 1];
    tableData[index - 1] = temp;

}

// 下移
const handleClickDown = (index: number) => {
    let temp = tableData[index];

    tableData[index] = tableData[index + 1];
    tableData[index + 1] = temp;
}

</script>

<style>
.tableDataArea {
    height: calc(100vh - 160px);
}
</style>
